package com.example.readerapp;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.icu.lang.UScript;
import android.net.Uri;
import android.os.*;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.*;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.readerapp.myandserver.mybookconfig.BookInfoTable;
import com.example.readerapp.myandserver.mybookconfig.MyBookConfig;
import com.example.readerapp.myandserver.mybookconfig.*;
import com.example.readerapp.myandserver.util.FormatSaveUtil;
import com.example.readerapp.myandserver.util.ZipUtil;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.example.readerapp.myandserver.mybookconfig.MyBookConfig.*;

public class MainActivity extends AppCompatActivity
{

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    //以上三个用于实现webview上传页面
    WebView webView=null;
    //AndServer服务
    Server server=null;
   private  Handler handler=new Handler(){
       @Override
       public void handleMessage(Message msg)
       {
           switch (msg.what){
               case 1:
                   Toast.makeText(MainActivity.this,"未授予文件读写权限",Toast.LENGTH_LONG).show();
                   break;
               case 2:
                   Toast.makeText(MainActivity.this,"AndServer服务器异常",Toast.LENGTH_LONG).show();
               case 3:
                   AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
               default:break;
           }
       }

   };
   private ProgressBar progressBar=null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_main_1);
        getSupportActionBar().hide();//隐藏自带标题栏
        //使用夜间模式，注意和同时使用andserver会出现问题：
        //销毁activity但是andserver还在运行，这时不要再次尝试运行（判断一下andserver是否为空）
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            //隐藏顶部状态栏，底部导航栏
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            View decorView = getWindow().getDecorView();
            //隐藏状态栏和导航栏
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
           //隐藏导航栏而不隐藏状态栏，需要布局文件配合
         //   decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            //请求文件读写权限，地三个参数为请求码，用于区分是在哪里发起的请求
        //Toast.makeText(this,Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 222);
    }
    //当申请文件读写权限后回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        int hasPermission= ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        System.out.println("请求权限结果："+hasPermission);
        if(hasPermission==-1)
        {
            //用户拒绝授予权限
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    Message message=new Message();
                    message.what=1;
                    handler.sendMessage(message);
                }
            }).start();

        }
        else//授予权限
        {
             progressBar = findViewById(R.id.progressBar);
            // Toast.makeText(this,Environment.getExternalStorageDirectory().getAbsolutePath(),Toast.LENGTH_LONG).show();
             initDir(this,Environment.getExternalStorageDirectory().getAbsolutePath());//初始化各种书籍有关信息’
            //new BookInfoTable().deleteTable();
            //new BookInfoTable().creatBookInfoTable();
            switch (requestCode)
            {
                    case 222:
                       // Toast.makeText(getApplicationContext(), "已申请权限", Toast.LENGTH_SHORT).show();
                        //构建服务
                        if(server==null)
                        server = AndServer.webServer(this).port(8080).timeout(10, TimeUnit.SECONDS).listener(new Server.ServerListener()
                        {
                                    @Override
                                    public void onStarted()
                                    {
                                        System.out.println("服务启动");
                                    }

                                    @Override
                                    public void onStopped()
                                    {
                                        System.out.println("服务停止");
                                    }

                                    @Override
                                    public void onException(Exception e)
                                    {
                                        progressBar.setVisibility(View.GONE);
                                        new Thread(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                Message message = new Message();
                                                message.what = 2;
                                                handler.sendMessage(message);
                                            }
                                        }).start();
                                        System.out.println("服务异常");
                                    }
                                }).build();
                        //启动服务
                        if(server!=null&&!server.isRunning())
                        server.startup();
                        initWebView();
                        //防止服务器还没启动就访问
                        while (server == null || !server.isRunning()) ;
                        {
                        progressBar.setVisibility(View.GONE);
                        webView.loadUrl("http://localhost:8080/main");
                        //webView.loadUrl("https://www.yhdmw.cc/content/6886.html");
                        //webView.loadUrl("https://www.dongmankk.com/play/id/119725/sid/1/nid/1.html");
                        //webView.loadUrl("https://www.bilibili.com/");

                            // webView.setVisibility(View.VISIBLE);
                        }
                    default:
                        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                }

        }


    }



    @Override
    //可能有问题,感觉没什么用
    protected void onDestroy() {
         if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);

            webView.clearHistory(); ((ViewGroup)
                    webView.getParent()).removeView(webView);
            webView.destroy();
            webView = null;

        }
        //关闭服务
        if(server!=null)
        server.shutdown();

        super.onDestroy();

    }
    //重写返回按钮，防止直接退出activity
    //可以把所有url按照先后顺序放入一个List<String>做成一个返回栈,便于管理
    @Override
    public void onBackPressed()
    {
        String url= webView.getUrl();
       // Toast.makeText(this,url,Toast.LENGTH_SHORT).show();
        if(url.equals("http://localhost:8080/main"))
        {
            super.onBackPressed();
        }
        else if(url.equals("http://localhost:8080/lookbook"))
        {
            webView.loadUrl("http://localhost:8080/main");
            //判断一下配置信息是否以及写入完毕，若没有则提示用户不要关闭app
        }
        else
        {
            if(webView.canGoBack())
            {
                webView.goBack();
                webView.removeAllViews();
            }
        }
       /* if(webView.canGoBack())
        {
            webView.goBack();
            webView.removeAllViews();
        }
        else {
            // Toast.makeText(this,"无上一页",Toast.LENGTH_LONG).show();
            super.onBackPressed();
        }*/
    }
    //这个是按下音量-键返回
   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        String url= webView.getUrl();
       // Toast.makeText(this,url,Toast.LENGTH_SHORT).show();
        if(url.equals("http://localhost:8080/main"))
        {
            return super.onKeyDown(keyCode, event);
        }
        else if(url.equals("http://localhost:8080/lookbook"))
        {
            webView.loadUrl("http://localhost:8080/main");

        }
   /*     if(keyCode==KeyEvent.KEYCODE_BACK&& webView.canGoBack())
        {
            webView.goBack();
            webView.removeAllViews();
            return true;
        }
        //  Toast.makeText(this,"无上一页",Toast.LENGTH_LONG).show();
*/
    //    return true;
   // }

    private void initWebView()
    {
        //初始化控件
        webView=findViewById(R.id.wv_webview);

        //访问网页,防止打开系统浏览器
        webView.setWebViewClient(new WebViewClient(){


            //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(String.valueOf(request.getUrl()));
                return true;
            }
       //     String html="<a style=\" width:10px;height: 10px;border: red 3px solid;sposition: absolute;\n" + "            z-index: 1;\" href=\"http://localhost:8080/mainlooktv\">回到主页</a>\n";

            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                //view.loadUrl("javascript:myCallback.callback(document.querySelector('html').innerHTML);");
             //   view.loadUrl("javascript:let t=document.querySelector('html');t.innerHTML="+html);
                //  view.loadUrl("javascript:if(t==undefined||t==null) {alert('l');} else alert('a');");
              //  view.loadUrl("javascript:alert('xa')");
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                super.onPageStarted(view, url, favicon);
              //  view.loadUrl("javascript:let t=document.querySelector('html');t.innerHTML="+html);

                //view.loadUrl("javascript:myCallback.callback(document.querySelector('html').innerHTML);");
               // view.loadUrl("javascript:let t=document.querySelector('html');t.innerHTML=t.innerHTML+\"<div> 黄卫民</div>\"");
                //  view.loadUrl("javascript:if(t==undefined||t==null) {alert('l');} else alert('a');");


            }

        });
        //支持js的Alert(),加载时显示进度条,上传文件等
        webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                ProgressBar pg1=findViewById(R.id.progressBar1);
                if(newProgress==100){
                    pg1.setVisibility(View.GONE);//加载完网页进度条消失
                    //加载完毕之后在显示，用于解决刚打开app是一闪而过一个白色的东西
                    webView.setVisibility(View.VISIBLE);

                }
                else{
                    pg1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    pg1.setProgress(newProgress);//设置进度值
                }

            }



            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

        //激活WebView为活跃态，能正常执行网页的响应
        webView.onResume();
        //是否可以后退、前进
        webView.canGoBack();
        webView.canGoForward();
        //webView.setBackgroundColor(0);
        //webView.getBackground().setAlpha(0);

        WebSettings webSettings= webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许与js交互
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过js打开新窗口

        //下面一些设置不是很清楚
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

//        webSettings.setBuiltInZoomControls(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setUseWideViewPort(true); // 关键点
        webSettings.setAllowFileAccess(true); // 允许访问文件
        //webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//允许网页和网页资源混用Https和Http


    }



    /*下面这些用于实现文件上传*/
    // 2.回调方法触发本地选择文件
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");//图片上传
        //i.setType("file/*");//文件上传
        i.setType("*/*");//文件上传

        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    // 3.选择图片后处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else {
            //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
            //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
            //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            } else if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
        }
    }

    // 4. 选择内容回调到Html页面
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
}

